<template>
  <div class="container-box" id="container-box">
    <el-form :inline="true" :model="filter" class="form-inline">
      <el-form-item label="订单编号：">
        <el-input v-model="filter.order_number"></el-input>
      </el-form-item>
      <el-form-item label="支付状态：">
        <el-select v-model="filter.order_payment_status" clearable>
          <el-option label="未支付" value="0"></el-option>
          <el-option label="已支付" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间：">
        <el-col :span="11">
          <el-date-picker type="date" placeholder="选择日期" v-model="filter.payment_time_begin" format="yyyy 年 MM 月 dd 日" value-format="timestamp" style="width: 100%;"></el-date-picker>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-date-picker type="date" placeholder="选择时间" v-model="filter.payment_time_end" format="yyyy 年 MM 月 dd 日" value-format="timestamp" style="width: 100%;"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="filter.active" clearable>
          <el-option label="禁用" value="0"></el-option>
          <el-option label="可用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" icon="el-icon-search">查询</el-button>
        <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      stripe>
      <el-table-column
        prop="order_number"
        label="订单编号"
        width="218">
      </el-table-column>
      <el-table-column
        prop="order_amount"
        label="订单金额">
      </el-table-column>
      <el-table-column
        prop="order_discount"
        label="优惠金额">
      </el-table-column>
      <el-table-column
        prop="order_payment_amount"
        label="支付金额">
      </el-table-column>
      <el-table-column
        prop="order_payment_status"
        label="支付状态"
        :formatter="paymentStatusFormat">
      </el-table-column>
      <el-table-column
        prop="active"
        label="订单状态"
        :formatter="activeFormat">
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="创建时间"
        :formatter="dateFormat">
      </el-table-column>
      <el-table-column
        prop="update_time"
        label="最后更新时间"
        :formatter="dateFormat">
      </el-table-column>
      <el-table-column label="操作" width="243">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)"
            v-if="scope.row.order_payment_status === '0'">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            v-if="scope.row.order_payment_status === '0'">删除
          </el-button>
          <el-button
            size="mini"
            @click="handleQrcode(scope.row)"
            v-if="scope.row.order_payment_status === '0' && expireTimeCompare(scope.row)">二维码
          </el-button>
          <el-button
            size="mini"
            @click="handleView(scope.row)"
            v-if="scope.row.order_payment_status === '1'">查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="totalCount"
      background
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :total="totalCount">
    </el-pagination>
    <code-box ref="code" :codeUrl="codeUrl"></code-box>
    <el-dialog title="订单详情" :visible.sync="dialogTableVisible">
      <el-table :data="gridData">
        <el-table-column property="value" label="商品名称"></el-table-column>
        <el-table-column property="quantity" label="数量"></el-table-column>
        <el-table-column property="amount" label="金额"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { timestampToDate } from "../../assets/js/utils";
import codeBox from "../../components/code";
import createQrCodeImg from "../../assets/js/code";

export default {
  components: {
    codeBox
  },
  data() {
    return {
      filter: {
        order_number: "",
        order_payment_status: "",
        payment_time_begin: "",
        payment_time_end: "",
        active: ""
      },
      params: {
        "access-token": window.localStorage.getItem("token")
      },
      tableData: [],
      totalCount: 0,
      currentPage: 1,
      perPage: 10,
      codeUrl: "",
      timestamp: parseInt(new Date().getTime() / 1000),
      dialogTableVisible: false,
      gridData: []
    };
  },
  created: function() {
    this.getOrder();
  },
  methods: {
    updateId(data) {
      if (data) {
        let id = data.order_id;
        let idx = this.tableData.findIndex(ele => ele.order_id == id);
        if (idx > -1) {
          this.tableData[idx].order_payment_status = "1";
        }
      }
    },
    getOrder: function() {
      this.axios.get("orders", { params: this.params }).then(res => {
        this.tableData = res.data.data ? res.data.data.item : [];
        this.totalCount = res.data.data ? res.data.data._meta.totalCount : 0;
      });
    },
    deleteOrder: function(order_id) {
      this.axios
        .delete("orders/" + order_id, { params: this.params })
        .then(res => {
          if (res.data.code !== "1000") {
            this.$message({
              type: "error",
              message: res.data.message
            });
          } else {
            this.$message({
              type: "success",
              message: "删除成功!"
            });

            this.getOrder();
          }
        });
    },
    paymentStatusFormat(row, column) {
      let paymentStatus = row[column.property];

      if (
        !parseInt(paymentStatus) &&
        this.timestamp > parseInt(row.expire_time)
      ) {
        return "已失效";
      } else {
        return parseInt(paymentStatus) ? "已支付" : "未支付";
      }
    },
    dateFormat: function(row, column) {
      let date = row[column.property];
      if (date === undefined) {
        return "";
      } else {
        return timestampToDate(date);
      }
    },
    activeFormat: function(row, column) {
      let active = row[column.property];
      return parseInt(active) ? "可用" : "禁用";
    },
    handleEdit: function(row) {
      this.$router.push({
        path: "/Order/OrderEdit/" + row.order_id
      });
    },
    handleAdd: function() {
      this.$router.push({
        path: "/Order/OrderAdd"
      });
    },
    handleDelete: function(row) {
      this.$confirm("此操作将永久删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteOrder(row.order_id);
        })
        .catch(() => {});
    },
    handleQrcode(row) {
      let codeContent = row.payment_url;
      this.codeUrl = createQrCodeImg(codeContent);
      this.$refs.code.show();
    },
    handleView(row) {
      this.axios
        .get("orders/" + row.order_id, { params: this.params })
        .then(res => {
          let data = res.data.data.order.products;
          this.gridData = data;
          this.dialogTableVisible = true;
        });
    },
    onSubmit() {
      this.filter.order_number
        ? this.$set(this.params, "order_number", this.filter.order_number)
        : this.$delete(this.params, "order_number");
      this.filter.order_payment_status
        ? this.$set(
            this.params,
            "order_payment_status",
            this.filter.order_payment_status
          )
        : this.$delete(this.params, "order_payment_status");
      this.filter.payment_time_begin
        ? this.$set(
            this.params,
            "payment_time_begin",
            this.filter.payment_time_begin / 1000
          )
        : this.$delete(this.params, "payment_time_begin");
      this.filter.payment_time_end
        ? this.$set(
            this.params,
            "payment_time_end",
            this.filter.payment_time_end / 1000 + 86400 - 1
          )
        : this.$delete(this.params, "payment_time_end");
      this.filter.active
        ? this.$set(this.params, "active", this.filter.active)
        : this.$delete(this.params, "active");

      this.getOrder();
    },
    handleCurrentChange: function(page) {
      this.$set(this.params, "page", page);
      this.$set(this.params, "per-page", this.perPage);
      this.getOrder();
    },
    expireTimeCompare: function(row) {
      return row.expire_time >= parseInt(new Date().getTime() / 1000)
        ? true
        : false;
    }
  }
};
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>
